package softserve.vgolosh.tmn;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.filefilter.RegexFileFilter;

import softserve.vgolosh.utils.FileUtil;

public class TMNRegexFileFilter extends RegexFileFilter {
	private static final long serialVersionUID = 1L;
	private Matcher matcher;
	private Pattern pattern;
	private String searchRegex;
	private TMNSearchResults tmnSearchResults;
	private TMN currentTMN;
	private String currentClient;
	private TMNSearchResult founded = null;

	public TMNRegexFileFilter() {
		super("");
	}

	public TMNRegexFileFilter(String pattern, String searchRegex) {
		super(pattern);
		this.pattern = Pattern.compile(pattern);
		this.setSearchRegex(searchRegex);
	}

	@Override
	public boolean accept(File dir, String name) {
		matcher = pattern.matcher(name);
		if (!matcher.find()) {
			return false;
		}
		File file = new File(dir + System.getProperty("file.separator") + name);
		if (file.isDirectory()) {
			return false;
		}
		List<String> content = FileUtil.getContents(file.getAbsolutePath());
		Matcher curr_matcher = null;
		Pattern curr_pattern = Pattern.compile(searchRegex);
		for (String value : content) {
			curr_matcher = curr_pattern.matcher(value);
			if (curr_matcher.find()) {
				founded = new TMNSearchResult(file.getAbsolutePath(),
						currentClient, curr_matcher.group()
								+ " found in scope of note "
								+ currentTMN.getName());
				tmnSearchResults.add(founded);
				return true;
			}
		}
		return false;
	}

	public String getSearchRegex() {
		return searchRegex;
	}

	public void setPattern(String pattern) {
		this.pattern = Pattern.compile(pattern);
	}

	public void setSearchRegex(String searchRegex) {
		this.searchRegex = searchRegex;
	}

	public void setTmnSearchResults(TMNSearchResults tmnSearchResults) {
		this.tmnSearchResults = tmnSearchResults;
	}

	public TMNSearchResults getTmnSearchResults() {
		return tmnSearchResults;
	}

	public void setCurrentTMN(TMN currentTMN) {
		this.currentTMN = currentTMN;
	}

	public TMN getCurrentTMN() {
		return currentTMN;
	}

	public void setCurrentClient(String currentClient) {
		this.currentClient = currentClient;
	}

	public String getCurrentClient() {
		return currentClient;
	}

}
